<?php

include_once('Logging.php');

class RRExpressClass
{
    const USERNAME_TEST = '17321295203';                                                # 商户账号 人人快递提供   测试
    const APPKEY_TEST = 'c693dd1c4594de59311ab4e2d1d0d381';                             # appKey 人人快递提供 测试

    const  URL = '';                                                                    # 下单接口地址【正式环境】
    const  URL_TEST = 'http://code.rrkd.cn/v2/';                                        # 下单接口地址【测试环境】

    private $isDebug = true;
    private $user_name = '';
    private $app_key = '';
    public function __construct($flag,$user_name,$app_key)
    {
        $this->isDebug = $flag;
        $this->user_name = $user_name;
        $this->app_key = $app_key;
    }



    /**
     * 计价
     * @param $postData 参数数组
     * @param $timeStamp 时间戳
     * @param $startingAddress 发货地址
     * @param $consigneeAddress 收货地址
     * @param $timeout
     * @return bool|string
     */
    public function jj($sendData,$timeStamp,$startingAddress,$consigneeAddress,$timeout){
        $userName = (($this->isDebug) ? self::USERNAME_TEST : ($this->user_name));
        $checkword = (($this->isDebug) ? self::APPKEY_TEST : ($this->app_key));

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'getfastprice';
        $sign = strtolower(md5($checkword . md5($timeStamp) . strtolower(md5($userName . $startingAddress . $consigneeAddress))));
        $timeout = 10;

        $parameter = $sendData;
        $parameter['userName'] = $userName;                                             # 人人快递分配的第三方平台账号
        $parameter['sign'] = $sign;                                                     # 签名
        $parameter['callbackUrl'] = 'http://zhaipei.shjieta.com.cn/?md=service&cl=service&at=GetRRCallBack';                       # 订单状态变化回调通知地址
        $header [] = "Content-Type: application/json";
        $header [] = "timestamp:" . $timeStamp;
        $result =$this->curlPost($url, json_encode($parameter), $timeout, $header);
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        echo '<pre>';
        var_dump($result);die;
        return $result;
    }



    /**
     * 下单
     * @param $postData 参数数组
     * @param $timeStamp 时间戳
     * @param $startingAddress 发货地址
     * @param $consigneeAddress 收货地址
     * @param $timeout
     * @return bool|string
     */
    public function send_parameter($sendData){
        $userName = (($this->isDebug) ? self::USERNAME_TEST : ($this->user_name));
        $checkword = (($this->isDebug) ? self::APPKEY_TEST : ($this->app_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'addorderfortdd';
        $timeStamp = date('Y-m-d');
        $sign = strtolower(md5($checkword . md5($timeStamp) . strtolower(md5($userName . $sendData['deliver_address'] . $sendData['receiver_address']))));
        $timeout = 10;
        # 分割组合收货人 省市 直辖市（人人 若为直辖市，收货人的“consigneeProvince”为空）
        $province = mb_strpos($sendData['receiver_address'],'省');
        if($province){
            $p = explode('省',$sendData['receiver_address']);
            $c = explode('市',$p[1]);
            $p[0] = $p[0].'省';
            $c[0] = $c[0].'市';
        }else{
            $p = explode('市',$sendData['receiver_address']);
            $c[0] = $p[0].'市';
            $p[0] = '';
        }


        # 发货人是否直辖市
        $send_province = mb_strpos($sendData['deliver_province'],'省');
        if($send_province){
            $province_send = $sendData['deliver_province'];
            $city_send = $sendData['deliver_city'];
            $area_send = $sendData['deliver_area'];
        }else{
            $city = Data::$_city_code;
            if(in_array($sendData['deliver_province'],$city)){
                $province_send = '';
                $city_send = $sendData['deliver_city'];
                $area_send = $sendData['deliver_area'];
            }else{
              return '地区错误';
            }
        }

        $productsCount = count($sendData['products']);
        if($productsCount>1){
            $parameter['goodsName'] = $sendData['products'][0]['product_name'].'等';             # 货物名称
        }else{
            $parameter['goodsName'] = $sendData['products'][0]['product_name'];             # 货物名称
        }
        $parameter['goodsWeight'] = $sendData['actual_weight'];                         # 商品重量
        $parameter['goodsWorth'] = (int)$sendData['actual_pay'];                        # 商品价值
        $parameter['startingProvince'] = $province_send;                                # 发货人省份(标准的省，如北京、四川省)
        $parameter['startingCity'] = $city_send;                                        # 发货人城市(标准的市，如北京市、成都市)
        $parameter['startingAddress'] = $sendData['deliver_address'];                   # 发货人详细地址


        $parameter['consigneeProvince'] = $p[0];                                        # 收货人省份
        $parameter['consigneeCity'] = $c[0];                                            # 收货人城市
        $parameter['consigneeAddress'] = $sendData['receiver_address'];                 # 收货人详细地址
        $parameter['startingPhone'] = $sendData['deliver_tel'];                         # 发货人电话
        $parameter['startingName'] = $sendData['shop_name'];                            # 发货人姓名
        $parameter['consigneeName'] = $sendData['receiver'];                            # 收货人姓名
        $parameter['consigneePhone'] = $sendData['receiver_tel'];                       # 收货人联系电话
        $parameter['businessNo'] = $sendData['shop_express_no'];                        # 第三方订单号
        $parameter['pickupTime'] = $sendData['shop_pickup_time'];                        # 预约时间（24小时制）
        $parameter['serviceFees'] = 0;                                                  # 加价
        $parameter['userName'] = $userName;                                             # 人人快递分配的第三方平台账号
        $parameter['sign'] = $sign;                                                     # 签名
        $parameter['callbackUrl'] = $sendData['callbackUrl'].'?md=service&cl=service&at=GetRRCallBack';                       # 订单状态变化回调通知地址
        $header [] = "Content-Type: application/json";
        $header [] = "timestamp:" . $timeStamp;
        $result =$this->curlPost($url, json_encode($parameter), $timeout, $header);
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }


    /**
     * 取消订单
     * @param $timeStamp    时间戳
     * @param $businessNo   第三方订单号
     * @param $reason   原因
     * @param $timeout
     * @return bool|string
     */
    function cancel($timeStamp,$businessNo,$reason,$timeout){
        $userName = (($this->isDebug) ? self::USERNAME_TEST : ($this->user_name));
        $checkword = (($this->isDebug) ? self::APPKEY_TEST : ($this->app_key));

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'cancelorder';
        $sign = strtolower(md5($checkword . md5($timeStamp) . (md5($userName .  $businessNo))));
        $cancelData['userName'] = $userName;
        $cancelData['reason'] = $reason;
        $cancelData['businessNo'] = $businessNo;
        $cancelData['sign'] = $sign;
        $header [] = "Content-Type: application/json";
        $header [] = "timestamp:" . $timeStamp;
        $result =$this->curlPost($url, json_encode($cancelData), $timeout, $header);
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }


    /**
     * 查询订单
     * @param $timeStamp    时间戳
     * @param $businessNo 第三方订单号
     * @param $orderNo  人人订单号
     * @param $timeout
     * @return bool|string
     */
    function query($timeStamp,$businessNo,$timeout){
        $userName = (($this->isDebug) ? self::USERNAME_TEST : ($this->user_name));
        $checkword = (($this->isDebug) ? self::APPKEY_TEST : ($this->app_key));

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'queryorder';
        $sign = strtolower(md5($checkword . md5($timeStamp) . (md5($userName .  $businessNo))));
        $queryData['userName'] = $userName;
        $queryData['businessNo'] = $businessNo;
        $queryData['sign'] = $sign;
        $header [] = "Content-Type: application/json";
        $header [] = "timestamp:" . $timeStamp;
        $result =$this->curlPost($url, json_encode($queryData), $timeout, $header);
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }

    /**
     * 重新下单
     * @param $businessNo   第三方订单号
     * @param $startingAddress  发货人地址
     * @param $consigneeAddress 收货人地址
     * @param $timeout
     * @return bool|string
     */
    function aging($timeStamp,$agingPostData,$startingAddress,$consigneeAddress,$businessNo,$timeout){
        $userName = (($this->isDebug) ? self::USERNAME_TEST : ($this->user_name));
        $checkword = (($this->isDebug) ? self::APPKEY_TEST : ($this->app_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'againorder';
        $sign = strtolower(md5($checkword . md5($timeStamp) . (md5($userName .  $startingAddress.$consigneeAddress))));
        $agingPostData['userName'] = $userName;
        $agingPostData['businessNo'] = $businessNo;
        $agingPostData['sign'] = $sign;
        $header [] = "Content-Type: application/json";
        $header [] = "timestamp:" . $timeStamp;
        $result =$this->curlPost($url, json_encode($agingPostData), $timeout, $header);
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }

    /**
     *  获取订单配送人信息
     * @param $timeStamp 时间戳
     * @param $businessNo 第三方订单号
     * @param $timeout
     * @return bool|string
     */
    function getorderdeliverer($timeStamp,$businessNo,$timeout){
        $userName = (($this->isDebug) ? self::USERNAME_TEST : ($this->user_name));
        $checkword = (($this->isDebug) ? self::APPKEY_TEST : ($this->app_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'getorderdeliverer';
        $sign = strtolower(md5($checkword . md5($timeStamp) . (md5($userName .  $businessNo.$userName))));    # 测试下 商户手机号和平台分配账号一样
        $getOrderDelivererPostData['userName'] = $userName; # 测试下 商户手机号和平台分配账号一样
        $getOrderDelivererPostData['customerPhone'] = $userName;    # 测试下 商户手机号和平台分配账号一样
        $getOrderDelivererPostData['businessNo'] = $businessNo;
        $getOrderDelivererPostData['sign'] = $sign;
        $header [] = "Content-Type: application/json";
        $header [] = "timestamp:" . $timeStamp;
        $result =$this->curlPost($url, json_encode($getOrderDelivererPostData), $timeout, $header);
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }

    /**
     * 查询账户余额
     * @param $timeStamp 时间戳
     * @param $timeout
     * @return bool|string
     */
    function blance($timeStamp,$timeout){
        $userName = (($this->isDebug) ? self::USERNAME_TEST : ($this->user_name));
        $checkword = (($this->isDebug) ? self::APPKEY_TEST : ($this->app_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'user/blance/index';
        $sign = md5(md5($timeStamp). md5($userName) . md5($checkword));
        $blancePostData['userName'] = $userName;
        $blancePostData['sign'] = $sign;
        $header [] = "Content-Type: application/json";
        $header [] = "timestamp:" . $timeStamp;
        $result =$this->curlPost($url, json_encode($blancePostData), $timeout, $header);
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }


    /**
     * 查询订单轨迹
     * @param $timeStamp 时间戳
     * @param $businessNo 第三方订单号
     * @param $timeout
     * @return bool|string
     */
    function trail($timeStamp,$businessNo,$timeout){
        $userName = (($this->isDebug) ? self::USERNAME_TEST : ($this->user_name));
        $checkword = (($this->isDebug) ? self::APPKEY_TEST : ($this->app_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'trail';
        $sign = MD5($checkword . MD5($timeStamp) . MD5($userName .$businessNo));
        $blancePostData['userName'] = $userName;
        $blancePostData['businessNo'] = $businessNo;
        $blancePostData['sign'] = $sign;
        $header [] = "Content-Type: application/json";
        $header [] = "timestamp:" . $timeStamp;
        $result =$this->curlPost($url, json_encode($blancePostData), $timeout, $header);
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }

    /**
     * 模拟订单状态回调
     * @param $timeStamp    时间戳
     * @param $businessNo   第三方订单号
     * @param $orderStatus  订单状态
     * @param $operationType 状态
     * @param $timeout
     * @return bool|string
     */
    function testCallback($timeStamp,$businessNo,$orderStatus,$operationType,$timeout){
        $userName = (($this->isDebug) ? self::USERNAME_TEST : ($this->user_name));
        $checkword = (($this->isDebug) ? self::APPKEY_TEST : ($this->app_key));
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'callback';
        $sign = MD5($checkword .MD5($timeStamp). MD5($userName ));
        $blancePostData['userName'] = $userName;
        $blancePostData['businessNo'] = $businessNo;
        $blancePostData['orderStatus'] = $orderStatus;
        $blancePostData['operationType'] = $operationType;
        $blancePostData['sign'] = $sign;
        $header [] = "Content-Type: application/json";
        $header [] = "timestamp:" . $timeStamp;
        $result =$this->curlPost($url, json_encode($blancePostData), $timeout, $header);
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }

    /**
     * @param $url 请求地址
     * @param array $post_data 数组
     * @param int $timeout
     * @param array $header 头部信息
     * @param bool $post_File 文件无
     * @return bool|string
     */
    function curlPost($url, $post_data = array(), $timeout = 15, $header = array(), $post_File = false) {
        $log = new Logging();
        $post_string = null;
        if (is_array ( $post_data ) && ! $post_File) {
            $post_string = http_build_query ( $post_data );
        } else {
            $post_string = $post_data;
        }

        $oCurl = curl_init ();
        curl_setopt ( $oCurl, CURLOPT_POST, true );
        curl_setopt ( $oCurl, CURLOPT_POSTFIELDS, $post_string );
        curl_setopt ( $oCurl, CURLOPT_URL, $url );
        curl_setopt ( $oCurl, CURLOPT_RETURNTRANSFER, true );
        curl_setopt ( $oCurl, CURLOPT_CONNECTTIMEOUT, $timeout );
        curl_setopt ( $oCurl, CURLOPT_TIMEOUT, $timeout );
        curl_setopt ( $oCurl, CURLOPT_HTTPHEADER, $header ); // 模拟的header头

        $time=strtotime(date('Y-m-d H:i:s'));
        $log->lfile('rr_express');
        $log->lwrite($time.','.($url));
        $log->lwrite($time.','.json_encode(json_decode($post_data, true), JSON_UNESCAPED_UNICODE));

        $result = curl_exec ( $oCurl );
        $aStatus = curl_getinfo($oCurl);    # 获取传输信息
        curl_close ( $oCurl );
        if (intval($aStatus["http_code"]) == 200) {
            return $result;
        } else {
            return false;
        }
    }



}

?>